import { withPageContainer } from '@/components';
import  styles from './index.module.less';
import { useEffect, useState } from 'react';
import { Tabs } from '@nutui/nutui-react-taro';
import { View } from '@tarojs/components';
import { useUserStore } from '@/common/hox/userStore';
import Taro, { usePullDownRefresh, useReachBottom } from '@tarojs/taro';
import { useRequest } from 'ahooks';
import { getUserMovieOrders } from '@/service';
import { useInitStore } from '@/common/hox/initStore';
import OrderCard from './components/OrderCard';

const orderPage = () => {
    // 当前选中的tab值
    const [tabvalue, setTabvalue] = useState<string | number>('0');
    // 订单列表数据
    const [orderList, setOrderList] = useState([] as any);
    // 用户信息和登录方法，从自定义store获取
    const { userInfo, loginAsync } = useUserStore();
    const { initReady } = useInitStore();
    // 分页相关配置
    const [pageObj, setPageObj] = useState<object>({
        pageSize: 10,
        pageIndex: 1,
    });
    const [total, setTotal] = useState(0);
    // tab配置，包含tab标题和对应的值
    const tabMap: {
        title: string;
        value: string;
    }[] = [
        { title: '全部', value: '0' },
        { title: '待付款', value: '1' },
        { title: '待出票', value: '3,4' },
        { title: '已出票', value: '5' },
    ];

    // 构建请求参数
    const getOrderParams = (pageParams = pageObj) => ({
        ...(tabvalue === '3,4'
            ? { multiOrderStatus: tabvalue }
            : { orderStatus: String(tabvalue) }),
        ...pageParams,
    });

    // 获取订单列表
    const getUserMovieOrdersApi = useRequest(
        async (isLoadMore = false) => {
            Taro.showLoading({
                title:'加载中'
            });
            const currentParams = isLoadMore
                ? {
                      pageSize: 10,
                      pageIndex: Math.ceil(orderList.length / 10) + 1,
                  }
                : pageObj;

            const res = await getUserMovieOrders(getOrderParams(currentParams));
            return { ...res, isLoadMore };
        },
        {
            ready: initReady && !!userInfo?.userId,
            onSuccess: ({ list, total, isLoadMore }) => {
                setTotal(total);
                setOrderList(isLoadMore ? [...orderList, ...list] : list);
                if (isLoadMore) {
                    setPageObj({
                        pageSize: 10,
                        pageIndex: Math.ceil((orderList.length + list.length) / 10),
                    });
                }
            },
            onFinally: () => {
                setTimeout(() => Taro.hideLoading(), 300);
            },
        }
    );

    // 监听依赖变化重新获取订单
    useEffect(() => {
        if (tabvalue && initReady && userInfo?.userId) {
            getUserMovieOrdersApi.runAsync(false).catch(console.error);
        }
    }, [tabvalue, initReady, userInfo?.userId]);

    // 下拉刷新
    usePullDownRefresh(() => {
        setPageObj({
            pageSize: 10,
            pageIndex: 1,
        });
        setTimeout(async () => {
            await getUserMovieOrdersApi?.runAsync(false);
            Taro.stopPullDownRefresh();
        }, 100);
    });

    // 上拉加载更多
    useReachBottom(async () => {
        if (!userInfo?.userId || orderList.length >= total) return;
        await getUserMovieOrdersApi?.runAsync(true);
    });

    // 数据组件，根据用户登录状态和订单列表显示不同内容
    const Data = () => {
        // 未登录时显示登录提示
        if (!userInfo?.userId) {
            return (
                <View>
                    <div className={styles.infinite}>
                        <div className={styles.emptyWrap}>
                            <div className={styles.icNotLogin} />
                            <div className={styles.text}>还没有登录哦，请先登录</div>
                            <div className={styles.btn} onClick={() => loginAsync()}>
                                登录
                            </div>
                        </div>
                    </div>
                </View>
            );
        }
        // 已登录但没有订单时显示无订单提示
        if (userInfo?.userId && !orderList.length) {
            return (
                <div className={styles.emptyWrap}>
                    <div className={styles.emptyLogo} />
                    <div className={styles.text}>一个订单都没有哦，犒劳一下自己，先下一单</div>
                    <div
                        className={styles.btn}
                        onClick={() => Taro.reLaunch({ url: '/pages/index/index' })}
                    >
                        返回首页
                    </div>
                </div>
            );
        } else {
            return (
                <>
                    {orderList.map((item) => (
                        <View key={item.id}>
                            <OrderCard
                                item={item}
                                onRefresh={() => getUserMovieOrdersApi?.runAsync()}
                            />
                        </View>
                    ))}
                </>
            );
        }
    };

    // 渲染Tabs，每个tab下都显示空数据组件
    return (
        <Tabs
            value={tabvalue}
            tabStyle={{ position: 'sticky', top: 0, zIndex: 11 }}
            onChange={(value) => {
                if (!userInfo?.userId) return;
                setTabvalue(value);
            }}
            // activeColor='var(--color-main)'
        >
            {tabMap.map((tab) => (
                <Tabs.TabPane title={tab.title} key={tab.value} value={tab.value}>
                    <Data />
                </Tabs.TabPane>
            ))}
        </Tabs>
    );
};
export default withPageContainer(orderPage);
